package sixkey.Exception.handler;

/**
 * ClassName:Handler
 * Package:sixkey.Exception
 * Description
 *
 * @Author:@wenxueshi
 * @Create:2023/5/20 - 16:40
 * @Version:v1.0
 */

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import sixkey.Exception.*;
import sixkey.utils.ResCodeEnum;
import sixkey.utils.ResResult;

import java.net.BindException;

/**
 * 统一异常处理
 */
@RestControllerAdvice //统一异常处理注解
@Slf4j
public class GlobalExceptionHandler {

    //此注解可以捕捉到SystemException抛出的异常
    @ExceptionHandler(SystemException.class)
    public ResResult systemExceptionHandler(SystemException systemException){
        log.info("出现了异常：",systemException);
        return ResResult.errorResult(systemException.getCode(),systemException.getMessage());
    }

    //对未知异常进行一个兜底
    @ExceptionHandler(Exception.class)
    public ResResult exceptionHandler(Exception exception){
        log.info("出现了异常：",exception);
        return ResResult.errorResult(ResCodeEnum.SYSTEM_ERROR.getCode(),exception.getMessage());
    }

    //参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResResult bindException(MethodArgumentNotValidException e){
        log.info("出现了异常：",e);
        return ResResult.errorResult(ResCodeEnum.SYSTEM_ERROR.getCode(),e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    //用户名已存在
    @ExceptionHandler(UserNameExistException.class)
    public ResResult UserNameExistException(UserNameExistException e){
        log.info("出现了异常：",e);
        return ResResult.errorResult(ResCodeEnum.USERNAME_EXIST.getCode(),e.getMessage());
    }

    //用户已被删除
    @ExceptionHandler(UserIsDeletedException.class)
    public ResResult UserIsDeletedException(UserIsDeletedException e){
        log.info("出现了异常：",e);
        return ResResult.errorResult(ResCodeEnum.USERIS_DELETED.getCode(),e.getMessage());
    }

    //用户名不存在
    @ExceptionHandler(UserNameNotFoundException.class)
    public ResResult UserNameNotFoundException(UserNameNotFoundException e){
        log.info("出现了异常：",e);
        return ResResult.errorResult(ResCodeEnum.USERNAME_NOTFOUND.getCode(),e.getMessage());
    }

    //密码错误
    @ExceptionHandler(PasswordErrorException.class)
    public ResResult PasswordErrorException(PasswordErrorException e){
        log.info("出现了异常：",e);
        return ResResult.errorResult(ResCodeEnum.LOGIN_ERROR.getCode(),e.getMessage());
    }
}
